<?php
/**
 * 简单的用户系统
 * 头像验证、用户组、实名认证
 * @author wolf
 * @since 2014-07-12
 *
 */
class MemberService implements IMember {
	
	const USERNAME = 'username';
	// 系统默认管理员 权限从上到下 默认是5
	public $_group = array (1 => "站长", 2 => "管理员", 3 => "实名用户", 4 => "注册会员", 5 => "游客", 6 => "黑名单", 0 => "继承分类权限" );
	//分页数
	private $_num = 40;
	// 用来区分等级
	// 用户等级制度
	public $_verify = array ("-1" => "不通过", "0" => "尚未认证", "1" => "实名认证" );
	public $_status = array ("0" => "在职", "1" => "离职" );
	
	/**
	 * 保存用户
	 */
	public function save($user) {
		
		if (! empty ( $user ['password'] )) {
			$salt = $this->randstr ();
			$data ['password'] = md5 ( md5 ( $user ['password'] ) . $salt );
			$data ['salt'] = $salt;
		}
		
		if (! empty ( $_FILES ['face'] ['tmp_name'] )) {
			$data ['face'] = $this->upload ();
		}
		
		$data ['email'] = trim ( $user ['email'] );
		$data ['mobile_phone'] = trim ( $user ['mobile_phone'] );
		$data ['country'] = trim ( $user ['country'] );
		$data ['area'] = trim ( $user ['area'] );
		$data ['real_name'] = trim ( $user ['real_name'] );
		$data ['username'] = trim ( $user ['username'] );
		$data ['groupid'] = $user ['groupid'];
		$data ['verify'] = $user ['verify'];
		$data ['manager'] = $user ['manager'];
		$data ['status'] = $user ['status'];
		MemberModel::instance ()->setMemberByWhere ( $data, array ('uid' => $user ['uid'] ) );
		return self::SUCCESS;
	}
	//修改用户真实信息
	public function saveMemberAddress($uid, $address) {
		if (empty ( $uid )) {
			return "请先登录";
		}
		
		if (empty ( $address )) {
			return "地址不能为空";
		}
		$rs = MemberModel::instance ()->setMemberByWhere ( array ('area' => trim ( $address ) ), array ('uid' => $uid ) );
		return $rs > 0 ? "更新成功,感谢你的参与" : "更新失败";
	}
	
	/**
	 * 增加用户
	 */
	public function register($userInfo) {
		
		if (! $this->checkValidate ( $userInfo ['codeimg'] )) {
			return "验证码错误";
		}
		
		if (strlen ( $userInfo ['mobile_phone'] ) != 11) {
			return "手机号码为11位数";
		}
		
		if (strlen ( $userInfo ['password'] ) < 5) {
			return "密码至少为5位数";
		}
		
		if (strlen ( $userInfo ['username'] ) < 3) {
			return "用户名至少为3位数";
		}
		
		if ($this->filter ( $userInfo ['password'] )) {
			return "密码中包含了标点符号";
		}
		
		if ($this->filter ( $userInfo ['username'] )) {
			return "用户名中包含了标点符号";
		}
		
		if (! $this->checkRepeat ( 'mobile_phone', $userInfo ['mobile_phone'] )) {
			return "手机号码重复了!";
		}
		if (! $this->checkRepeat ( 'username', $userInfo ['username'] )) {
			return "帐号重复了!";
		}
		
		return $this->addMember ( $userInfo );
	
	}
	
	/**
	 * 新增用户
	 * @param Array $userInfo
	 */
	private function addMember($userInfo) {
		$salt = $this->randstr ();
		$data ['username'] = trim ( $userInfo ['username'] );
		$data ['real_name'] = trim ( $userInfo ['real_name'] );
		$data ['password'] = md5 ( md5 ( $userInfo ['password'] ) . $salt );
		$data ['salt'] = $salt;
		$data ['add_time'] = time ();
		$ip = $this->getIp ();
		$data ['country'] = $ip ['country'];
		$data ['area'] = $ip ['country'];
		$data ['mobile_phone'] = trim ( $userInfo ['mobile_phone'] );
		//防止非法修改
		$data ['groupid'] = $userInfo ['groupid'];
		//注册用户权限
		$data ['manager'] = 4;
		$data ['verify'] = 0;
		//直接验证成功
		$lastinsertId = MemberModel::instance ()->addMember ( $data );
		
		return $lastinsertId < 1 ? self::ERROR : self::SUCCESS;
	
	}
	
	public function login($user) {
		if (! $this->checkValidate ( $user ['codeimg'] )) {
			return "验证码错误";
		}
		
		if ($this->filter ( $user ['password'] )) {
			return '密码中含有标点符号';
		}
		
		$userInfo = $this->isLogin ( $user ['mobile_phone'], $user ['password'] );
		//这里的$userInfo 返回一个对象 现在是数组
		if (! is_array ( $userInfo )) {
			return $userInfo;
		}
		//增加登录历史记录
		MemberModel::instance ()->updateMember ( array ('lastlogin' => time () ), array ('uid' => $userInfo ['uid'] ) );
		
		return $userInfo;
	}
	
	/**
	 * 检测验证码是否正确
	 */
	private function checkValidate($codeimg) {
		if (! isset ( $codeimg )) {
			return false;
		}
		if (trim ( $codeimg ) != $_SESSION ["authnum_session"]) {
			return false;
		}
		return true;
	}
	
	public function getMemberGroup() {
		return MemberModel::instance ()->getGroupAll ();
	}
	//加密方法
	public function randstr($len = 6) {
		$chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
		mt_srand ( ( double ) microtime () * 1000000 * getmypid () );
		$password = '';
		while ( strlen ( $password ) < $len ) {
			$password .= substr ( $chars, (mt_rand () % strlen ( $chars )), 1 );
		}
		return $password;
	}
	/**
	 * 检查用户是否重复
	 */
	private function checkRepeat($key, $value) {
		$rs = MemberModel::instance ()->getOneMember ( array ($key => trim ( $value ) ) );
		return empty ( $rs );
	}
	
	//修改用户属性
	public function setMemberValue($v, $uid) {
		$rs = MemberModel::instance ()->setMemberByWhere ( $v, array ('uid' => $uid ) );
		return $rs > 0 ? self::SUCCESS : self::ERROR;
	}
	
	/**
	 * 获取用户信息
	 * @param int $uid
	 * @return Array
	 */
	public function getMemberByUid($uid) {
		return MemberModel::instance ()->getOneMember ( array ('uid' => $uid ) );
	}
	
	public function getMemberByWhere($where) {
		return MemberModel::instance ()->getOneMember ( $where );
	}
	
	/**
	 * 判断是否登录
	 * @param String $username
	 * @param String $passsword
	 * @return Array 用户信息
	 */
	private function isLogin($username, $passsword) {
		
		//下面调用服务
		// 查询用户是否存在
		$userInfo = MemberModel::instance ()->getOneMember ( array ('mobile_phone' => $username ) );
		
		// 简单验证
		if (empty ( $userInfo )) {
			return "手机号码不存在";
		}
		if (strlen ( $username ) < 4 || strlen ( $passsword ) < 4) {
			return "用户名或密码不能小与6位!";
		}
		// 判断密码是否正确
		if ($userInfo ['password'] != md5 ( md5 ( $passsword ) . $userInfo ['salt'] )) {
			return "密码不正确";
		
		}
		
		//检查账号是否被禁用
		if ($userInfo ['status'] > 0) {
			return "账号已被禁用!";
		}
		
		return $userInfo;
	
	}
	
	/**
	 * 用户账户状态
	 * @param string $ids
	 * @param string $type
	 */
	public function saveStatus($ids, $type) {
		
		$data = substr ( trim ( $ids ), 1 );
		// 只复制一个的情况
		if (strpos ( $data, "," )) {
			$data = explode ( ",", $data );
			foreach ( $data as $v ) {
				if ($type == "refuse") {
					$rs = MemberModel::instance ()->setMemberByWhere ( array ('verify' => - 1, 'manager' => 4 ), array ('uid' => $v ) );
				}
				if ($type == "pass") {
					$rs = MemberModel::instance ()->setMemberByWhere ( array ('verify' => 1, 'manager' => 3 ), array ('uid' => $v ) );
				}
			}
		} else {
			if ($type == "refuse") {
				$rs = MemberModel::instance ()->setMemberByWhere ( array ('verify' => - 1, 'manager' => 4 ), array ('uid' => $data ) );
			}
			if ($type == "pass") {
				$rs = MemberModel::instance ()->setMemberByWhere ( array ('verify' => 1, 'manager' => 3 ), array ('uid' => $data ) );
			}
		}
		return self::SUCCESS;
	}
	/**
	 * 
	 * 管理用户钱袋子
	 * @param int $uid
	 * @param decimal $coupons
	 * @param int $type  0增加 1减少
	 */
	public function saveCoupons($uid, $coupons, $type) {
		$user = $this->getMemberByUid ( $uid );
		if ($type < 1) {
			$coupons = $user ['coupons'] + $coupons;
		} else {
			$coupons = $user ['coupons'] - $coupons;
		}
		return $this->setMemberValue ( array ('coupons' => $coupons ), $uid );
	}
	
	/**
	 * 后台头像上传处理
	 * 注意上传文件大小限制
	 *
	 * @return string $filePath 图片路径
	 */
	public function upload() {
		if (is_uploaded_file ( $_FILES ['face'] ['tmp_name'] )) {
			$upfile = $_FILES ['face'];
			$name = $upfile ['name'];
			$type = $upfile ['type'];
			$size = $upfile ['size'];
			$tmp_name = $upfile ['tmp_name'];
			$error = $upfile [error];
			switch ($type) {
				case 'image/jpeg' :
					$ok = 1;
					break;
				case 'image/pjpeg' :
					$ok = 1;
					break;
				case 'image/gif' :
					$ok = 1;
					break;
				case 'image/png' :
					$ok = 1;
					break;
				case 'image/x-png' :
					$ok = 1;
					break;
			}
			// 修正缩略图文件夹
			// 创建文件夹
			$save_path = getcwd () . "/static/attached/face/";
			$save_url = "./static/attached/face/";
			$ym = date ( "Ym" );
			$save_path .= $ym . "/";
			$save_url .= $ym . "/";
			if (! file_exists ( $save_path )) {
				mkdir ( $save_path );
			}
			if ($ok == '1' && $error == '0') {
				$fileType = substr ( $name, strpos ( $name, "." ) + 1 );
				$newName = time () . "." . $fileType;
				$filepath = $save_path . $newName;
				move_uploaded_file ( $tmp_name, $filepath );
				
				$callback = $_REQUEST ["CKEditorFuncNum"];
				
				return $save_url . $newName;
			} else {
				return self::ERROR;
			}
		}
	}
	
	/**
	 * 获取ip
	 */
	private function getIp() {
		$ip = new IpLocation ();
		$clientIp = $ip->getIP ();
		$rs = $ip->getlocation ( $clientIp );
		unset ( $rs ['beginip'] );
		unset ( $rs ['endip'] );
		foreach ( $rs as $k => $v ) {
			$v = iconv ( 'GB2312', 'UTF-8', $v );
			$arrIp [$k] = $v;
		}
		return $arrIp;
	}
	
	public function getOneMemberByUsername($username) {
		return MemberModel::instance ()->getOneMember ( array (self::USERNAME => $username ) );
	}
	
	/**
	 * 
	 * 搜索
	 */
	public function search($field, $value) {
		$rs = MemberModel::instance ()->getMemberByLike ( $field, $value );
		// 重组验证和等级
		foreach ( $rs as $k => $v ) {
			$rs [$k] ['verify'] = $this->_verify [$v ['verify']];
			$rs [$k] ['groupid'] = $this->_group [$v ['groupid']];
			$rs [$k] ['status'] = $this->_status [$v ['status']];
		
		}
		return $rs;
	}
	
	/**
	 * 删除会员 
	 * @param int $uid
	 */
	public function remove($uid, $actionUserId) {
		
		if ($uid < 1) {
			return "id必须大于1";
		}
		
		if ($uid == $actionUserId) {
			return "无法删除自己";
		}
		
		$user = $this->getMemberByUid ( $uid );
		
		if (empty ( $user )) {
			return "用户不存在";
		}
		if (round ( $user ['coupons'] ) > 1) {
			return "用户积分还有剩余,无法删除";
		}
		
		$rs = MemberModel::instance ()->delMemberByWhere ( array ('uid' => $uid ) );
		return $rs > 0 ? self::SUCCESS : self::ERROR;
	}
	
	public function listing($currentPage, $data) {
		$where = null;
		
		$group = $this->getMemberGroup ();
		//系统组别
		foreach ( $group as $v ) {
			$groupname [$v ['id']] = $v ['name'];
		}
		//设置条件
		$filter = array ('p', 'mb' );
		
		foreach ( $data as $k => $v ) {
			if ($k === "") {
				continue;
			}
			
			if ($v === "") {
				continue;
			}
			
			if (in_array ( $k, $filter )) {
				continue;
			}
			
			$where [$k] = $v;
		
		}

		$totalNum = MemberModel::instance ()->countMember ( $where );
		$page = $this->page ( $currentPage, $totalNum );
		$memberlist = MemberModel::instance ()->getPages ( $page ['start'], $page ['num'], $where, "uid DESC" );
		// 重组验证和等级
		foreach ( $memberlist as $k => $v ) {
			$memberlist [$k] ['verify'] = $this->_verify [$v ['verify']];
			$memberlist [$k] ['groupid'] = $this->_group [$v ['groupid']];
			$memberlist [$k] ['status'] = $this->_status [$v ['status']];
		
		}
		return array ('totalnum' => $totalNum, 'memberlist' => $memberlist, 'groupname' => $groupname, 'verify' => $this->_verify, 'page' => $page );
	}
	
	/**
	 * 用户修改密码
	 * @param int $uid
	 * @param String $password
	 * @param String $newPassword
	 */
	public function rePassword($uid, $password, $newPassword) {
		$user = MemberModel::instance ()->getOneMember ( array ('uid' => trim ( $uid ) ) );
		$oldPassword = md5 ( md5 ( $password ) . $user ['salt'] );
		
		if ($this->filter ( $newPassword )) {
			return "密码中请勿包含标点符号等";
		}
		
		if ($newPassword == "123456") {
			return "密码过于简单";
		}
		
		if ($newPassword == $password) {
			return "新的密码和旧密码不能相同";
		}
		
		if (strlen ( $newPassword ) < 5) {
			return "密码至少为6位";
		}
		
		if ($user ['password'] != $oldPassword) {
			return "原密码错误";
		} else {
			$this->rePasssword ( $uid, trim ( $newPassword ) );
			return "修改成功,下次登录时生效";
		}
	}
	
	/**
	 * 修改密码
	 * @param unknown_type $uid
	 * @param unknown_type $password
	 */
	private function rePasssword($uid, $password) {
		$salt = MemberModel::instance ()->getOneMember ( array ('uid' => trim ( $uid ) ) );
		MemberModel::instance ()->setMemberByWhere ( array ('password' => md5 ( md5 ( $password ) . $salt ['salt'] ) ), array ('uid' => trim ( $uid ) ) );
	}
	/**
	 * 检测是否包含非法字符
	 * @return boolean true or false
	 */
	private function filter($str) {
		$pattern = "#[\*\.\/\?\-\%\!]+#i";
		return preg_match ( $pattern, $str );
	}
	
	/**
	 * 分页
	 *
	 * @return void
	 */
	private function page($p, $total) {
		
		$pageid = isset ( $p ) ? $p : 1;
		$start = ($pageid - 1) * $this->_num;
		$pagenum = ceil ( $total / $this->_num );
		return array ('start' => $start, 'num' => $this->_num, 'current' => $pageid, 'page' => $pagenum );
	
	}
}